'use strict';

exports.main = async (event, context) => {
	const db = uniCloud.database()
	if (event.actionType === 'query') {
		let pageSize = event.pageSize;
		let pageNum = event.pageNum;
		let orderBy = event.orderBy === 1 ? 'asc' : 'desc';
		const res = await db.collection('message').limit(pageSize).skip((pageNum - 1) * pageSize)
			.orderBy("createTime", orderBy).get()
		if (res) {
			return {
				code: 200,
				msg: '查询成功',
				data: res
			}
		} else {
			return {
				code: 201,
				msg: '查询失败'
			}
		}
	}
	if (event.actionType === 'add') {
		let res = await db.collection('message').add({
			nickname: event.nickname,
			avatarUrl: event.avatarUrl,
			content: event.content,
			createTime: event.createTime,
			openid:event.openid
		})
		console.log(res);
		if (res.id) {
			return {
				code: 200,
				msg: '留言成功'
			}
		} else {
			return {
				code: 201,
				msg: '留言失败'
			}
		}
	}
	if (event.actionType === 'del') {
		let res = await db.collection('message').doc(event.id).remove()
		if (res.deleted) {
			return {
				code: 200,
				msg: '删除成功'
			}
		} else {
			return {
				code: 201,
				msg: '删除失败'
			}
		}
	}
};
